package com.sailorless.net 
{
	/**
	 * ...
	 * @author Herbs
	 */
	public class LoaderQueue 
	{
		private var queues:Vector.<LoaderAdapter>;
		private var wcLoader:WebClient;
		
		public function LoaderQueue() 
		{
			queues = new Vector.<LoaderAdapter>();
			wcLoader = new WebClient();
		}
		
		public function start():void 
		{
			loadItem();
		}
		
		public function add(adapter:LoaderAdapter):void 
		{
			queues.push(adapter);
			queues.sort(sortByIndex);
		}
		
		private function loadItem():void 
		{
			var queueSize:int = queues.length;
			if (queueSize > 0)
			{
				queues.sort(sortByIndex);
				var ada:LoaderAdapter = queues[queueSize-1];
				wcLoader.fnDownloadComplete = onComplete;
				wcLoader.fnDownloadError = onError;
				wcLoader.fnDownloadProgress = ada.fnProgress;
				wcLoader.fnDownloadTimeOut = onTimeout;
				switch(ada.type)
				{
					case WebClient.STRING:
						wcLoader.downloadString(ada.addr);
						break;
					case WebClient.BINARY:
						wcLoader.downloadData(ada.addr);
						break;
					case WebClient.IMAGE:
						wcLoader.downloadImage(ada.addr, ada.async);
						break;
					case WebClient.TXML:
						wcLoader.downloadXML(ada.addr);
						break;
					case WebClient.MOVIECLIP:
						wcLoader.downloadSWF(ada.addr);
						break;n
				}
			}
			
		}
		
		private function onError():void 
		{
			queues[queues.length-1].fnError.apply(null);
			queues.pop();
			if (queues.length > 0)
				loadItem();
		}
		
		private function onComplete(data:*):void 
		{
			queues[queues.length-1].fnComplete.apply(null, [data]);
			queues.pop();
			if (queues.length > 0)
				loadItem();
		}
		
		private function onTimeout():void 
		{
			queues[queues.length-1].fnTimeout.apply(null);
			queues.pop();
			if (queues.length > 0)
				loadItem();
		}
		
		
		private function sortByIndex(a1:LoaderAdapter, a2:LoaderAdapter):Boolean 
		{
			return a1.index > a2.index;
		}
		
	}

}